package cn.xuedeng.point.controller;

import cn.xueden.common.redis.service.RedisService;
import cn.xueden.service.RocketMQProducer;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@Slf4j
@RestController
@Api(tags = "积分兑换金币")
@RequestMapping("/edu/exchange")
public class EduExchangeController {

    @Resource
    private RocketMQProducer rocketMQProducer;

    @Autowired
    private RedisService redisService;

    @Autowired
    RedissonClient redissonClient;

    private static final String lockPrefix = "point::lock::acount";

    @PostMapping("/toGold")
    @ApiImplicitParams(value = {@ApiImplicitParam(name = "accountId", value = "用户id"),
        @ApiImplicitParam(name = "num", value = "兑换数量")})
    public Integer pointToGold(@RequestParam("account") Long accountId, @RequestParam("num") Integer num,
        @RequestParam("pointId") Long pointId) {
        //校验积分是否足够兑换

        //新增用户金币

        //扣减用户积分

        return 0;
    }

    @PostMapping("/addPoint")
    public Integer addPoint(Long pointId){
        //使用分布式锁确保查询&添加是原子操作
        String lockName = lockPrefix + pointId;
        RLock lock = redissonClient.getLock(lockName);
        Boolean ret=false;
        Integer changeAfter=0;
        try {
            lock.lock();
            //查询原来积分,更新chanageAfter

            //添加记录,更新ret

        } catch (Exception e) {
            log.info("添加积分异常{}", JSON.toJSONString(e));
        } finally {
            lock.unlock();
        }
        //发送积分变更消息(勋章变更)
        if(ret){
            sendPoint();
        }
        return changeAfter;
    }

    /**
     * 由上游服务产生
     */
    public void sendPoint(){
        String msg = "point++";
        rocketMQProducer.sendMsg(msg);
    }

}
